import React, { useState, useEffect, useRef } from 'react';
import { Input, Button, List, message, Card, Space, Select, Modal, Avatar } from 'antd';
import { SendOutlined, LinkOutlined, DisconnectOutlined, UserOutlined } from '@ant-design/icons';
import './App.css';

const { TextArea } = Input;

function App() {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [connected, setConnected] = useState(false);
  const [loading, setLoading] = useState(false);
  const [currentRoom, setCurrentRoom] = useState('general');
  const [username, setUsername] = useState('');
  const [userId] = useState(() => `user_${Math.random().toString(36).substr(2, 9)}`);
  const [onlineUsers, setOnlineUsers] = useState([]);
  const [privateModalVisible, setPrivateModalVisible] = useState(false);
  const [privateMessage, setPrivateMessage] = useState('');
  const [selectedUser, setSelectedUser] = useState(null);
  const ws = useRef(null);

  // 连接WebSocket
  const connectWebSocket = () => {
    if (!username.trim()) {
      message.warning('请输入用户名');
      return;
    }

    setLoading(true);
    ws.current = new WebSocket(`ws://localhost:8000/ws/${currentRoom}/${userId}/${username}`);
    
    ws.current.onopen = () => {
      setConnected(true);
      setLoading(false);
      message.success(`已连接到聊天室 ${currentRoom}`);
    };
    
    ws.current.onmessage = (e) => {
      try {
        const data = JSON.parse(e.data);
        
        switch(data.type) {
          case 'chat':
          case 'system':
            setMessages(prev => [...prev, data]);
            if (data.online_users) {
              setOnlineUsers(data.online_users);
            }
            break;
          case 'private':
            message.info(`收到来自 ${data.from.username} 的私信`);
            setMessages(prev => [...prev, data]);
            break;
          case 'private_sent':
            message.success(data.content);
            break;
          default:
            setMessages(prev => [...prev, data]);
        }
      } catch (err) {
        console.error('消息解析错误:', err);
      }
    };
    
    ws.current.onclose = () => {
      setConnected(false);
      message.warning('已断开WebSocket连接');
    };
    
    ws.current.onerror = (err) => {
      console.error('WebSocket错误:', err);
      message.error('连接错误');
      setLoading(false);
    };
  };

  // 断开连接
  const disconnectWebSocket = () => {
    if (ws.current) {
      ws.current.close();
    }
  };

  // 发送消息
  const sendMessage = () => {
    if (!connected) {
      message.warning('请先连接WebSocket');
      return;
    }
    
    if (!inputValue.trim()) {
      message.warning('消息不能为空');
      return;
    }
    
    const messageData = {
      content: inputValue,
      timestamp: new Date().getTime()
    };
    
    ws.current.send(JSON.stringify(messageData));
    setInputValue('');
  };

  // 发送私信
  const sendPrivateMessage = () => {
    if (!selectedUser) {
      message.warning('请选择要私聊的用户');
      return;
    }
    
    if (!privateMessage.trim()) {
      message.warning('私信内容不能为空');
      return;
    }
    
    const privateData = {
      type: "private",
      to_user_id: selectedUser.user_id,
      content: privateMessage,
      timestamp: new Date().getTime()
    };
    
    ws.current.send(JSON.stringify(privateData));
    setPrivateMessage('');
    setPrivateModalVisible(false);
  };

  // 打开私信模态框
  const showPrivateModal = (user) => {
    setSelectedUser(user);
    setPrivateModalVisible(true);
  };

  // 组件卸载时断开连接
  useEffect(() => {
    return () => {
      if (ws.current) {
        ws.current.close();
      }
    };
  }, []);

  return (
    <div className="app-container">
      <Card 
        title="WebSocket私聊示例" 
        bordered={false}
        extra={
          <Space>
            {!connected ? (
              <>
                <Input
                  placeholder="输入用户名"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  style={{ width: 120 }}
                />
                <Button
                  type="primary"
                  icon={<LinkOutlined />}
                  onClick={connectWebSocket}
                  loading={loading}
                >
                  连接
                </Button>
              </>
            ) : (
              <Button
                danger
                icon={<DisconnectOutlined />}
                onClick={disconnectWebSocket}
              >
                断开
              </Button>
            )}
          </Space>
        }
      >
        <div className="chat-container">
          {/* 在线用户列表 */}
          <div className="online-users">
            <h4>在线用户 ({onlineUsers.length})</h4>
            <List
              dataSource={onlineUsers}
              renderItem={user => (
                <List.Item 
                  actions={[
                    <Button 
                      type="link" 
                      size="small"
                      onClick={() => showPrivateModal(user)}
                    >
                      私信
                    </Button>
                  ]}
                >
                  <List.Item.Meta
                    avatar={<Avatar icon={<UserOutlined />} />}
                    title={user.username}
                    description={`ID: ${user.user_id}`}
                  />
                </List.Item>
              )}
            />
          </div>
          
          {/* 消息列表 */}
          <div className="message-list">
            <List
              itemLayout="horizontal"
              dataSource={messages}
              renderItem={item => (
                <List.Item
                  style={{
                    background: item.type === 'private' ? '#f6ffed' : 'transparent',
                    borderLeft: item.type === 'private' ? '3px solid #52c41a' : 'none'
                  }}
                >
                  <List.Item.Meta
                    avatar={<Avatar icon={<UserOutlined />} />}
                    title={
                      <>
                        {item.user?.username || item.from?.username || '系统'} 
                        {item.type === 'private' && (
                          <span style={{ color: '#52c41a', marginLeft: 8 }}>[私信]</span>
                        )}
                        <span style={{ fontSize: 12, color: '#999', marginLeft: 8 }}>
                          {item.time}
                        </span>
                      </>
                    }
                    description={item.content}
                  />
                </List.Item>
              )}
            />
          </div>
          
          {/* 输入区域 */}
          <div className="input-area">
            <Input
              value={inputValue}
              onChange={e => setInputValue(e.target.value)}
              onPressEnter={sendMessage}
              placeholder="输入消息..."
              disabled={!connected}
            />
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={sendMessage}
              disabled={!connected}
            >
              发送
            </Button>
          </div>
        </div>
      </Card>
      
      {/* 私信模态框 */}
      <Modal
        title={`发送私信给 ${selectedUser?.username || ''}`}
        visible={privateModalVisible}
        onOk={sendPrivateMessage}
        onCancel={() => setPrivateModalVisible(false)}
      >
        <TextArea
          rows={4}
          value={privateMessage}
          onChange={e => setPrivateMessage(e.target.value)}
          placeholder="输入私信内容..."
        />
      </Modal>
    </div>
  );
}

export default App;